package pers.lance.scanpackage;

import java.io.File;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;

/**
 * @ Author     ：LILA3
 * @ Date       ：Created in 1:40 PM 7/24/2018
 */
public class ClassManager {

    private Map<String, Class<?>> classes = new HashMap<String, Class<?>>();
    private ClassLoader classLoader = ClassManager.class.getClassLoader();
    private static ClassManager classManager;

    public ClassManager() throws URISyntaxException {

    }

    public void scan(String packPath) throws URISyntaxException {
        scanClassLoacl(packPath);
    }


    public static ClassManager getInstance() throws URISyntaxException {
        if (classManager == null) {
            synchronized (ClassManager.class) {
                if (classManager == null) {
                    classManager = new ClassManager();
                }
            }
        }
        return classManager;
    }

    private void scanClassLoacl(String packPath) throws URISyntaxException {
        URL source = classLoader.getResource(packPath.replace(".", File.separator));
        File file = new File(source.toURI());
        file.listFiles((filepath) -> {
            if (filepath.isDirectory()) {
                try {
                    scanClassLoacl(packPath);
                } catch (URISyntaxException e) {

                }
            }
            if (filepath.getName().endsWith(".class")) {
                Class<?> clazz = null;
                String className = filepath.getName().replace(".class", "");
                try {
                    clazz = classLoader.loadClass(packPath + "." + className);
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }
                System.out.println("loading............." + clazz.getName());
                classes.put(className, clazz);
                return true;
            }
            return false;
        });
    }

}
